package me.monster.grideaprocessor;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description
 * @author: Created jiangjiwei in 2020/9/30 13:25
 */
class HtmlParser {
    public static final String utf8 = "UTF-8";
    public static final String html = "html";
    private Map<String, String> replaceMap = new HashMap<>();
    private List<String> resNameList = new ArrayList<>();
    private String relativeRootName = "";
    public static final String awesomeCssCdn = "https://cdn.bootcdn.net/ajax/libs/font-awesome/5.7.2/css/all.css";
    public static final String awesomeCss = "https://use.fontawesome.com/releases/v5.7.2/css/all.css";


    private HtmlParser() {

    }

    public static HtmlParser getInstance() {
        return new HtmlParser();
    }

    String parse(boolean inRoot, String path, String relativeRootName) {
        if (!path.endsWith(html)) {
            System.err.println("文件解析异常：" + path);
            return "";
        }
        this.relativeRootName = relativeRootName;
        buildReplaceMap();
        String newHtml = "";
        try {
            final Document parse = Jsoup.parse(new File(path), utf8);
            for (Element element : parse.getAllElements()) {
                for (Attribute it : element.attributes().asList()) {
                    String attrValue = it.getValue();
                    if (attrValue.contains("http") || attrValue.contains("https")) {
                        for (String replaceKey : replaceMap.keySet()) {
                            if (attrValue.contains(replaceKey)) {
                                attrValue = attrValue.replace(replaceKey, replaceMap.get(replaceKey));
                                break;
                            }
                        }
                        if (!attrValue.startsWith("http")) {
                            if (inRoot) {
                                if (attrValue.indexOf("/") != attrValue.lastIndexOf("/")) {
                                    int startIndex = 0;
                                    if (attrValue.startsWith("/")) {
                                        startIndex = 1;
                                    }
                                    String parent = attrValue.substring(startIndex, attrValue.indexOf("/", startIndex));
                                    if (resNameList.contains(parent)) {
                                        attrValue = getRelativePath(path, attrValue);
                                        attrValue = attrValue.substring(attrValue.indexOf(parent));
                                    }
                                } else {

                                }
                            } else {
                                if (attrValue.contains("/")) {
                                    String parent = attrValue.substring(0, attrValue.indexOf("/"));
                                    if (resNameList.contains(parent)) {
                                        attrValue = getRelativePath(path, attrValue);
                                    }
                                }
                            }
                        }
                        it.setValue(attrValue);
                    }

                    if ("link".equals(element.tagName())) {
                        if (element.attr("rel").equals("stylesheet") && element.attr("href").equals(awesomeCssCdn)) {
                            element.removeAttr("integrity");
                            element.removeAttr("crossorigin");
                        }

                        if ("shortcut icon".equals(element.attr("rel"))) {
                            element.attr("href", "favicon.ico?v=" + System.currentTimeMillis());
                        }
                    }
                }
            }
            newHtml = parse.html();
        } catch (IOException e) {
            e.printStackTrace();
            newHtml = "";
        }
        return newHtml;
    }

    private String getRelativePath(String path,  String attrValue) {
        String relativePath = path.substring(path.indexOf(relativeRootName) + relativeRootName.length() + 1);
        StringBuilder sb = new StringBuilder();
        for (char c : relativePath.toCharArray()) {
            if (c == '/') {
                sb.append("../");
            }
        }
        sb.append(attrValue);
        return sb.toString();
    }

    private void buildReplaceMap() {
        replaceMap.put("https://cherrylover.github.io/", "");
        replaceMap.put(awesomeCss, awesomeCssCdn);
        replaceMap.put("http://localhost:4000/", "");

        resNameList.add("styles");
        resNameList.add("post-images");
        resNameList.add("images");
        resNameList.add("page");
        resNameList.add("post");
    }
}
